<template>
  <div class="page-content user">
    <div class="content">
      <div class="right-wrap">
        <div class="info box-style">
          <h1 class="title">基本设置</h1>

          <el-form
            :model="formData"
            class="form"
            ref="formRef"
            :rules="rules"
            label-width="86px"
            label-position="top"
          >
          <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="头像" prop="usrHeadUrl">
              <div class="w-full">
                <MyUpload
                  :file-list="fileList"
                  :limit="1"
                  :width="'120px'"
                  :height="'120px'"
                  :disabled="!isEdit"
                  @deleteFile="deleteFile"
                  @uploadFileSuccess="success"

                />
              </div>
            </el-form-item>
          </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="账号" prop="usrNo">
                <el-input v-model="formData.usrNo" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="昵称" prop="usrName">
                <el-input v-model="formData.usrName" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="手机号" prop="usrPhone">
                <el-input v-model="formData.usrPhone" :disabled="!isEdit"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="usrSex">
                <el-select v-model="formData.usrSex" :disabled="!isEdit">
                  <el-option
                    v-for="(value, key) in usrSexMaps"
                    :key="key"
                    :label="value"
                    :value="key + 1"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
            <div class="el-form-item-right">
              <el-button type="primary" style="width: 90px" v-ripple @click="edit">
                {{ isEdit ? '保存' : '编辑' }}
              </el-button>
            </div>
          </el-form>
        </div>

        <div class="info box-style" style="margin-top: 20px">
          <h1 class="title">更改密码</h1>

          <el-form :model="pwdForm" class="form" label-width="86px" label-position="top">
            <!-- <el-form-item label="当前密码" prop="password">
              <el-input v-model="pwdForm.password" type="password" />
            </el-form-item> -->

            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="pwdForm.newPassword" type="password" />
            </el-form-item>
            <!-- :disabled="!isEditPwd" -->
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input v-model="pwdForm.confirmPassword" type="password" />
            </el-form-item>

            <div class="el-form-item-right">
              <el-button type="primary" style="width: 90px" v-ripple @click="editPwd">
                <!-- {{ isEditPwd ? '保存' : '编辑' }} -->
                保存
              </el-button>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { useUserStore } from '@/store/modules/user'
  import { FormInstance, FormRules } from 'element-plus'
  import { encryptPwd } from '@/utils/encryption'
  import { usrSexStatus } from '@/types/user'
  import { sysUserGetUserByIdUsingPost,sysUserUpdateUserUsingPost,sysUserChangePasswordUsingPut } from '@/api/4a/yonghu'
  const userStore = useUserStore()
  const userInfo = computed(() => userStore.getUserInfo)
  

  const isEdit = ref(false)
  const isEditPwd = ref(false)
  const date = ref('')
  const formData = reactive({
    usrHeadUrl: '',
    usrNo: '',
    usrName: '',
    usrPhone: '',
    usrSex: '',
  })

  // 获取用户详情并赋值给表单
  const getUserDetail = async (id: number) => {
    try {
      const res = await sysUserGetUserByIdUsingPost({
        body: { id },
        options: {}
      })
      if (res.code === 0 && res.data) {
        Object.assign(formData, res.data)
      }
    } catch (error) {
      console.error('获取用户详情失败:', error)
    }
  }

  // 监听用户信息变化
  watch(() => userInfo.value, (newVal) => {
    if (newVal?.id) {
      getUserDetail(newVal.id)
    }
  }, { immediate: true })

  const pwdForm = reactive({
    // password: '',
    newPassword: '',
    confirmPassword: ''
  })

  const ruleFormRef = ref<FormInstance>()

  const rules = reactive<FormRules>({
    realName: [
      { required: true, message: '请输入昵称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 30 个字符', trigger: 'blur' }
    ],
    nikeName: [
      { required: true, message: '请输入昵称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 30 个字符', trigger: 'blur' }
    ],
    email: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
    mobile: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
    address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
    sex: [{ type: 'array', required: true, message: '请选择性别', trigger: 'blur' }]
  })

  // 性别
  const usrSexMaps = Object.keys(usrSexStatus).map(
      (key) => usrSexStatus[key as keyof typeof usrSexStatus]
    )
  onMounted(() => {
    getDate()
  })

  const getDate = () => {
    const d = new Date()
    const h = d.getHours()
    let text = ''

    if (h >= 6 && h < 9) {
      text = '早上好'
    } else if (h >= 9 && h < 11) {
      text = '上午好'
    } else if (h >= 11 && h < 13) {
      text = '中午好'
    } else if (h >= 13 && h < 18) {
      text = '下午好'
    } else if (h >= 18 && h < 24) {
      text = '晚上好'
    } else if (h >= 0 && h < 6) {
      text = '很晚了，早点睡'
    }

    date.value = text
  }

  const edit = async() => {
   
    if(isEdit.value){
      const response = await sysUserUpdateUserUsingPost({
        body: formData
        })
        if (response.data) {
          isEdit.value = !isEdit.value
          ElMessage.success('保存成功')
        } else {
          ElMessage.error(response.msg)
        }
    }else{
      isEdit.value = !isEdit.value
    }
  }

  const editPwd = async () => {
    if (!pwdForm.newPassword || !pwdForm.confirmPassword) {
      ElMessage.error('请填写完整的密码信息')
      return
    }
    if (pwdForm.newPassword !== pwdForm.confirmPassword) {
      ElMessage.error('新密码和确认新密码不一致')
      return
    }
    try {
      const res = await sysUserChangePasswordUsingPut({
        params: {
          id: userInfo.value.id,
          password: encryptPwd(pwdForm.newPassword)
        }
      })
      if (res.code === 0 && res.data) {
        ElMessage.success('密码修改成功')
        pwdForm.newPassword = ''
        pwdForm.confirmPassword = ''
      } else {
        ElMessage.error(res.msg || '密码修改失败')
      }
    } catch (error) {
      ElMessage.error('密码修改异常')
    }
  }
  // 头像
  const fileList = computed({
    get() {
      return JSON.parse(formData.usrHeadUrl || '[]')
    },
    set(value) {
      formData.usrHeadUrl = value
    }
    })

    const success = (a:any) => {
      fileList.value.push(a.data)
      fileList.value = JSON.stringify(fileList.value)
    }

    const deleteFile = (params:any) => {
      fileList.value = JSON.stringify(fileList.value.filter((item:any) => item.path !== params.path))
    }
</script>

<style lang="scss">
  .user {
    .icon {
      width: 1.4em;
      height: 1.4em;
      overflow: hidden;
      vertical-align: -0.15em;
      fill: currentcolor;
    }
  }
</style>

<style lang="scss" scoped>
  .page-content {
    width: 100%;
    height: 100%;
    padding: 0 !important;
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;

    $box-radius: calc(var(--custom-radius) + 4px);

    .box-style {
      border: 1px solid var(--art-border-color);
    }

    .content {
      position: relative;
      display: flex;
      justify-content: space-between;
      margin-top: 10px;

      .left-wrap {
        width: 450px;
        margin-right: 25px;

        .user-wrap {
          position: relative;
          height: 600px;
          padding: 35px 40px;
          overflow: hidden;
          text-align: center;
          background: var(--art-main-bg-color);
          border-radius: $box-radius;

          .bg {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 200px;
            object-fit: cover;
          }

          .avatar {
            position: relative;
            z-index: 10;
            width: 80px;
            height: 80px;
            margin-top: 120px;
            object-fit: cover;
            border: 2px solid #fff;
            border-radius: 50%;
          }

          .name {
            margin-top: 20px;
            font-size: 22px;
            font-weight: 400;
          }

          .des {
            margin-top: 20px;
            font-size: 14px;
          }

          .outer-info {
            width: 300px;
            margin: auto;
            margin-top: 30px;
            text-align: left;

            > div {
              margin-top: 10px;

              span {
                margin-left: 8px;
                font-size: 14px;
              }
            }
          }

          .lables {
            margin-top: 40px;

            h3 {
              font-size: 15px;
              font-weight: 500;
            }

            > div {
              display: flex;
              flex-wrap: wrap;
              justify-content: center;
              margin-top: 15px;

              > div {
                padding: 3px 6px;
                margin: 0 10px 10px 0;
                font-size: 12px;
                background: var(--art-main-bg-color);
                border: 1px solid var(--art-border-color);
                border-radius: 2px;
              }
            }
          }
        }

        .gallery {
          margin-top: 25px;
          border-radius: 10px;

          .item {
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }
        }
      }

      .right-wrap {
        flex: 1;
        overflow: hidden;
        border-radius: $box-radius;

        .info {
          background: var(--art-main-bg-color);
          border-radius: $box-radius;

          .title {
            padding: 15px 25px;
            font-size: 20px;
            font-weight: 400;
            color: var(--art-text-gray-800);
            border-bottom: 1px solid var(--art-border-color);
          }

          .form {
            box-sizing: border-box;
            padding: 30px 25px;

            > .el-row {
              .el-form-item {
                width: calc(50% - 10px);
              }

              .el-input,
              .el-select {
                width: 100%;
              }
            }

            .right-input {
              margin-left: 20px;
            }

            .el-form-item-right {
              display: flex;
              align-items: center;
              justify-content: end;

              .el-button {
                width: 110px !important;
              }
            }
          }
        }
      }
    }
  }

  @media only screen and (max-width: $device-ipad-vertical) {
    .page-content {
      .content {
        display: block;
        margin-top: 5px;

        .left-wrap {
          width: 100%;
        }

        .right-wrap {
          width: 100%;
          margin-top: 15px;
        }
      }
    }
  }
</style>
